<script setup lang="ts">
import HandsonTable from 'handsontable'
import { registerAllModules } from 'handsontable/registry'
import 'handsontable/styles/handsontable.css'
import 'handsontable/styles/ht-theme-main.css'
// import 'handsontable/styles/ht-theme-horizon.css'
import '@/style/handsontable-theme.css'
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n'
import { HyperFormula } from 'hyperformula'

import useTheme from '../useTheme'
import { REPORT_FORM_ID, REPORT_ID } from '@/enum/modules/report'
import type { LoadDataResponse } from './type'
import { HEADER_CELL_CLASS, READONLY_CELL_CLASS, ROUND_NUMBER as _ROUND_NUMBER } from '../config'
import { loadReportDataOfSummaryCompanyElectricityCategory } from '@/api/modules/dataReport'

defineOptions({ name: 'SummaryCompanyElectricityCategory' })

const props = defineProps<{
  time: string
}>()

const ROUND_NUMBER = _ROUND_NUMBER + 2

registerLanguageDictionary(zhCN)

// register Handsontable's modules
registerAllModules()

// 分类用电情况汇总报表
// eslint-disable-next-line
const reportId = REPORT_ID.CLASSIFIED_ELECTRICITY_USAGE_SUMMARY
// eslint-disable-next-line
const formId = REPORT_FORM_ID.CLASSIFIED_ELECTRICITY_USAGE_SUMMARY
// 当前企业名称
// eslint-disable-next-line
const tenantName = ref('')
// 远程数据
const loadDataResponse = shallowRef<LoadDataResponse>()

const HEADERS = [
  [
    '单位名称',
    '煤矿用电量（kwh）',
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    '煤矿用电量合计（kwh）',
    '洗煤用电量',
    null,
    null,
    null,
    null,
    null,
    null,
    '洗煤用电量合计（kwh）',
    '煤矿、洗煤用电量合计（kwh）',
  ],
  [
    null,
    '生产用电量（kwh）',
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    '辅助生产用电量（kwh）',
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    '生产用电量（kwh）',
    null,
    null,
    null,
    '辅助生产用电（kwh）',
    null,
    null,
    null,
    null,
  ],
  [
    null,
    '主通风',
    '主排水',
    '空压机',
    '主提升机',
    '辅助运输',
    '综采生产',
    '掘进生产',
    '连采连充',
    '其他',
    '小计',
    '供热',
    '空气源热泵洗浴',
    '空气源热泵采暖',
    '瓦斯抽放泵站',
    '地面工业广场及附属设备',
    '其他',
    '外委施工',
    '小计',
    null,
    '主洗',
    '浮洗',
    '压滤',
    '小计',
    '生产辅助设备',
    '外委施工',
    '小计',
    null,
    null,
  ],
]

const wrapper = ref<HTMLElement>()
const hot = ref<HandsonTable>()

const newMergeCells = shallowRef<any[]>(
  [
    { row: 0, col: 0, rowspan: 3, colspan: 1 },
    { row: 1, col: 1, rowspan: 1, colspan: 10 },
    { row: 1, col: 11, rowspan: 1, colspan: 8 },
    { row: 1, col: 20, rowspan: 1, colspan: 4 },
    { row: 1, col: 24, rowspan: 1, colspan: 3 },
    { row: 0, col: 27, rowspan: 3, colspan: 1 },
    { row: 0, col: 28, rowspan: 3, colspan: 1 },
    { row: 0, col: 20, rowspan: 1, colspan: 7 },
    { row: 0, col: 19, rowspan: 3, colspan: 1 },
    { row: 0, col: 1, rowspan: 1, colspan: 18 },
  ],
)

// 加载数据
async function loadData() {
  if (!props.time)
    return
  const { data: res } = await loadReportDataOfSummaryCompanyElectricityCategory(props.time)
  const src: LoadDataResponse = loadDataResponse.value = res
  const list = src?.dataList ?? []
  const last = src?.lastMonthTotalData

  if (list.length) {
    const dataList = []
    // 各单位数据所在行号
    const rows: number[] = []
    for (let i = 0; i < list.length; i++) {
      // 单位数据行号
      const cur = i * 2 + 4
      const v = list[i]
      const array1 = []
      const array2 = []
      array1.push(
        v.subsidiaryName,
        v.mkZtf,
        v.mkZps,
        v.mkKyj,
        v.mkZtsj,
        v.mkFzys,
        v.mkZcsc,
        v.mkJjsc,
        v.mkLclc,
        v.mkScqt,
        // 生产小计
        `=ROUND(SUM(B${cur}:J${cur}),${ROUND_NUMBER})`,
        v.mkGr,
        v.mkXy,
        v.mkCn,
        v.mkWscfbz,
        v.mkFsss,
        v.mkFzqt,
        v.mkWwsg,
        // 辅助生产小计
        `=ROUND(SUM(L${cur}:Q${cur}),${ROUND_NUMBER})`,
        // 煤矿用电量合计（kwh）
        `=ROUND(K${cur}+S${cur},${ROUND_NUMBER})`,
        v.xmcZx,
        v.xmcFx,
        v.xmcLy,
        // 洗煤厂生产小计
        `=ROUND(SUM(U${cur}:W${cur}),${ROUND_NUMBER})`,
        v.xmcScfzss,
        v.xmcWwsg,
        // 洗煤厂辅助小计
        `=ROUND(SUM(Y${cur}:Z${cur}),${ROUND_NUMBER})`,
        // 洗煤厂用电量合计（kwh）
        `=ROUND(X${cur}+AA${cur},${ROUND_NUMBER})`,
        // 煤矿、洗煤用电量合计（kwh）
        `=ROUND(T${cur}+AB${cur},${ROUND_NUMBER})`,
      )
      array2.push(
        null,
        ...[...'BCDEFGHIJKLMNOPQRSTUVWXYZ', 'AA', 'AB', 'AC'].map((col) => {
          // 外委施工不参与占比计算
          if (['R', 'Z'].includes(col))
            return null
          return `=IFERROR(TEXT(ROUND(${col}${cur}/AC${cur}, ${ROUND_NUMBER})*100,"0.00%"), "")`
        }),
      )
      // 插入单位本月数据
      dataList.push(array1)
      // 插入单位占比数据
      dataList.push(array2)

      // 从行号4开始，每个单位占2行
      rows.push(i * 2 + 4)
    }

    // 插入各单位汇总行
    dataList.push([
      '各单位：',
      ...[...'BCDEFGHIJKLMNOPQRSTUVWXYZ', 'AA', 'AB', 'AC'].map((col) => {
        let exp = ''
        for (const row of rows) {
          exp += `${col}${row}+`
        }
        return `=ROUND(${exp.slice(0, -1)}, ${ROUND_NUMBER})`
      }),
    ])
    // 插入上月止累计行
    // 上月止累计所在行号
    const cur = rows[rows.length - 1] + 2 + 1
    dataList.push([
      '上月止：',
      last?.mkZtf ?? null,
      last?.mkZps ?? null,
      last?.mkKyj ?? null,
      last?.mkZtsj ?? null,
      last?.mkFzys ?? null,
      last?.mkZcsc ?? null,
      last?.mkJjsc ?? null,
      last?.mkLclc ?? null,
      last?.mkScqt ?? null,
      // 生产小计
      `=ROUND(SUM(B${cur}:J${cur}),${ROUND_NUMBER})`,
      last?.mkGr ?? null,
      last?.mkXy ?? null,
      last?.mkCn ?? null,
      last?.mkWscfbz ?? null,
      last?.mkFsss ?? null,
      last?.mkFzqt ?? null,
      last?.mkWwsg ?? null,
      // 辅助生产小计
      `=ROUND(SUM(L${cur}:Q${cur}),${ROUND_NUMBER})`,
      // 煤矿用电量合计（kwh）
      `=ROUND(K${cur}+S${cur},${ROUND_NUMBER})`,
      last?.xmcZx ?? null,
      last?.xmcFx ?? null,
      last?.xmcLy ?? null,
      // 洗煤厂生产小计
      `=ROUND(SUM(U${cur}:W${cur}),${ROUND_NUMBER})`,
      last?.xmcScfzss ?? null,
      last?.xmcWwsg ?? null,
      // 洗煤厂辅助小计
      `=ROUND(SUM(Y${cur}:Z${cur}),${ROUND_NUMBER})`,
      // 洗煤厂用电量合计（kwh）
      `=ROUND(X${cur}+AA${cur},${ROUND_NUMBER})`,
      // 煤矿、洗煤用电量合计（kwh）
      `=ROUND(T${cur}+AB${cur},${ROUND_NUMBER})`,
    ])
    if (rows[rows.length - 1] > 3) {
      const x = rows[rows.length - 1] + 2
      const y = x + 1
      // 插入本月止累计行
      dataList.push([
        '本月止：',
        ...[...'BCDEFGHIJKLMNOPQRSTUVWXYZ', 'AA', 'AB', 'AC'].map((col) => {
          return `=ROUND(${col}${x}+${col}${y},${ROUND_NUMBER})`
        }),
      ])

      // 占比
      dataList.push([
        null,
        '煤矿生产占比：',
        ...Array(8).fill(null),
        `=IFERROR(TEXT(ROUND(K${y + 1}/AC${y + 1},${ROUND_NUMBER})*100,"0.00%"), "")`,
        '煤矿辅助生产占比：',
        ...Array(6).fill(null),
        `=IFERROR(TEXT(ROUND(S${y + 1}/AC${y + 1},${ROUND_NUMBER})*100,"0.00%"), "")`,
        null,
        '洗煤生产占比：',
        ...Array(2).fill(null),
        `=IFERROR(TEXT(ROUND(X${y + 1}/AC${y + 1},${ROUND_NUMBER})*100,"0.00%"), "")`,
        '洗煤辅助生产占比：',
        null,
        `=IFERROR(TEXT(ROUND(AA${y + 1}/AC${y + 1},${ROUND_NUMBER})*100,"0.00%"), "")`,
        null,
        null,
      ])
    }

    hot.value?.loadData([
      ...HEADERS,
      ...dataList,
    ])
  }
}

// 更新单元格合并
function updateMergeCells() {
  if (hot.value) {
    const src = loadDataResponse.value
    const list = src?.dataList ?? []
    if (list.length === 0) {
      return
    }
    // 各单位数据所在行索引
    const rows: number[] = []
    for (let i = 0; i < list.length; i++) {
      rows.push(i * 2 + 3)
    }
    const mergeCells = [
      ...newMergeCells.value,
      // A列的每个单位合并2行
      ...rows.map((v) => {
        return { row: v, col: 0, rowspan: 2, colspan: 1 }
      }),
      // 最后一行
      { row: hot.value.countRows() - 1, col: 1, rowspan: 1, colspan: 9 },
      { row: hot.value.countRows() - 1, col: 11, rowspan: 1, colspan: 7 },
      { row: hot.value.countRows() - 1, col: 20, rowspan: 1, colspan: 3 },
      { row: hot.value.countRows() - 1, col: 24, rowspan: 1, colspan: 2 },
    ]

    hot.value.updateSettings({
      mergeCells,
      cell: [
        { row: hot.value.countRows() - 1, col: 1, className: 'htRight' },
        { row: hot.value.countRows() - 1, col: 11, className: 'htRight' },
        { row: hot.value.countRows() - 1, col: 20, className: 'htRight' },
        { row: hot.value.countRows() - 1, col: 24, className: 'htRight' },
      ],
    })
  }
}

function init() {
  if (!wrapper.value)
    return
  hot.value = new HandsonTable(wrapper.value, {
    fixedColumnsStart: 1,
    fixedRowsTop: HEADERS.length,
    readOnly: true,
    // disableVisualSelection: true,
    language: zhCN.languageCode,
    data: [...HEADERS],
    formulas: {
      engine: HyperFormula,
    },
    cells(row, column) {
      if (row < HEADERS.length || column < 1) {
        return { className: `htCenter htMiddle ${HEADER_CELL_CLASS}` }
      }
      return { className: `htCenter htMiddle` }
    },
    readOnlyCellClassName: READONLY_CELL_CLASS,
    stretchH: 'all',
    // autoColumnSize: true,
    colWidths: 100,
    manualColumnResize: true,
    // colWidths: (index) => {
    //   if (index === 0)
    //     return 150
    //   else if ([12, 13, 14].includes(index))
    //     return 130
    //   else if (index === 15)
    //     return 200
    //   else if ([19, 24, 27, 28].includes(index))
    //     return 230
    //   return 100
    // },
    colHeaders: true,
    rowHeaders: true,
    mergeCells: [
      ...newMergeCells.value,
    ],
    licenseKey: 'non-commercial-and-evaluation',
  })

  // debug
  if (import.meta.env.VITE_REPORT_DEBUG === '1') {
    hot.value.addHook('afterSelection', (row, col) => {
      if (row > -1 && col > -1) {
        console.info(`[${row},${col}] ${hot.value?.getSourceDataAtCell(row, col)}`)
        document.execCommand('copy')
      }
    })
  }
}

async function bootstrap() {
  // 初始化实例
  init()
  // 加载数据和配置
  await loadData()
  // 更新单元格合并
  updateMergeCells()
}

onMounted(bootstrap)

const { isDark } = useTheme(async () => {
  // 主题切换后，重新初始化实例
  if (hot.value) {
    hot.value.destroy()
    hot.value = undefined
    await bootstrap()
  }
})
</script>

<template>
  <div class="h-full w-full">
    <div
      ref="wrapper" class="h-full w-full overflow-auto" :class="{
        'ht-theme-main-dark': isDark,
        'ht-theme-main': !isDark,
      }"
    />
  </div>
</template>
